package com.ibeeking.found.msg.rest.service.impl;

import com.ibeeking.found.msg.rest.service.ISmsRelationService;
import com.ibeeking.found.msg.service.common.bo.MsgRelationBO;
import com.ibeeking.found.msg.service.common.constants.RedisKeyConstant;
import com.ibeeking.found.msg.service.common.dos.SmsRelationDO;
import com.ibeeking.found.msg.service.common.param.SmsRelationParam;
import com.ibeeking.found.msg.service.common.vo.MsgRelationVO;
import com.ibeeking.found.msg.service.mapper.SmsRelationMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.redis.annotation.CacheEvict;
import com.ibeeking.nematos.redis.annotation.CacheQuery;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @ClassName SmsRelationServiceImpl
 * @Description 消息关系实现类
 * @Author ibeeking
 * @Date 2020-12-10 9:31
 **/
@Service
public class SmsRelationServiceImpl extends ServiceImpl<SmsRelationMapper, SmsRelationDO> implements ISmsRelationService {

    @Resource
    private SmsRelationMapper smsRelationMapper;

    @Transactional
    @Override
    public Boolean modify(SmsRelationParam smsRelationParam) {
        SpringBeanUtil.getBean(ISmsRelationService.class).del(smsRelationParam.getTenantId(), smsRelationParam.getMsgTypeId());
        SmsRelationDO smsRelationDO = BeanUtil.convertBean(smsRelationParam, SmsRelationDO.class);

        return smsRelationMapper.insert(smsRelationDO) > 0;
    }

    @Override
    public MsgRelationVO view(Integer tenantId, Long msgTypeId) {
        MsgRelationBO msgRelationBO = SpringBeanUtil.getBean(ISmsRelationService.class).queryById(tenantId, msgTypeId);
        return BeanUtil.convertBean(msgRelationBO, MsgRelationVO.class);
    }

    @CacheQuery(cacheName = RedisKeyConstant.MODULE + RedisKeyConstant.MSG_RELATION, key = "#tenantId+':'+#msgTypeId", expires = RedisKeyConstant.HALF_DAY)
    @Override
    public MsgRelationBO queryById(Integer tenantId, Long msgTypeId) {
        SmsRelationDO smsRelationDO = smsRelationMapper.selectOne(new LambdaQueryWrapper<>(SmsRelationDO.class).eq(SmsRelationDO::getTenantId, tenantId).eq(SmsRelationDO::getMsgTypeId, msgTypeId));
        return BeanUtil.convertBean(smsRelationDO, MsgRelationBO.class);
    }

    @CacheEvict(cacheName = RedisKeyConstant.MODULE + RedisKeyConstant.MSG_RELATION, key = "#tenantId+':'+#msgTypeId")
    @Override
    public Boolean del(Integer tenantId, Long msgTypeId) {
        return smsRelationMapper.delete(new LambdaQueryWrapper<>(SmsRelationDO.class).eq(SmsRelationDO::getTenantId, tenantId).eq(SmsRelationDO::getMsgTypeId, msgTypeId)) > 0;
    }
}
